<template>
  <q-list>
    <template v-for="menu in menus" :key="menu.path">
      <!-- 有子菜单 -->
      <q-expansion-item
        v-if="menu.children?.length"
        :icon="menu.meta?.icon"
        :label="menu.meta?.title"
        :default-opened="isMenuOpen(menu.path)"
      >
        <q-list>
          <q-item
            v-for="subMenu in menu.children"
            :key="subMenu.path"
            v-show="checkPermission(subMenu)"
            :to="resolvePath(menu.path, subMenu.path)"
            clickable
            v-ripple
          >
            <q-item-section avatar v-if="subMenu.meta?.icon">
              <q-icon :name="subMenu.meta.icon" />
            </q-item-section>
            <q-item-section>{{ subMenu.meta?.title }}</q-item-section>
          </q-item>
        </q-list>
      </q-expansion-item>

      <!-- 无子菜单 -->
      <q-item v-else v-show="checkPermission(menu)" :to="menu.path" clickable v-ripple>
        <q-item-section avatar>
          <q-icon :name="menu.meta?.icon" />
        </q-item-section>
        <q-item-section>{{ menu.meta?.title }}</q-item-section>
      </q-item>
    </template>
  </q-list>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from 'stores/useUserStore'

const route = useRoute()
const userStore = useUserStore()

const menus = computed(() => userStore.menus)
console.log(menus.value)
// 检查菜单权限
const checkPermission = (menu) => {
  if (!menu.meta?.permission) return true
  return userStore.hasPermission(menu.meta.permission)
}

// 判断菜单是否展开
const isMenuOpen = (path) => {
  return route.path.startsWith(path)
}

// 添加这个函数来解析完整路径
const resolvePath = (basePath, path) => {
  if (path.startsWith('/')) {
    return path
  }
  return `${basePath}/${path}`.replace(/\/+/g, '/')
}
</script>
